// MissionControlPanel.js

class MissionControlPanel {
    static instance = null;

    static initialize() {
        if (MissionControlPanel.instance) {
            console.warn('MissionControlPanel already initialized');
            return MissionControlPanel.instance;
        }

        const maxAttempts = 10;
        let attempts = 0;

        const tryInitialize = () => {
            return new Promise((resolve, reject) => {
                const attempt = () => {
                    attempts++;
                    const container = document.getElementById('control-info');

                    if (container) {
                        try {
                            MissionControlPanel.instance = new MissionControlPanel(container);
                            console.log('Robot mission control panel initialized');
                            resolve(MissionControlPanel.instance);
                        } catch (error) {
                            reject(error);
                        }
                    } else if (attempts < maxAttempts) {
                        setTimeout(attempt, 100);
                    } else {
                        reject(new Error('Control panel container not found'));
                    }
                };

                attempt();
            });
        };

        return tryInitialize();
    }

    constructor(container) {
        if (MissionControlPanel.instance) {
            return MissionControlPanel.instance;
        }

        this.container = container;
        this.stateManager = window.robotStateManager;

        this.state = {
            battery: 0,
            status: 'idle',
            cleanMode: 'standard', // 默认清扫模式
            waterLevel: 1,
            suctionPower: 1,
            isConnected: false // 添加连接状态标志
        };

        this.init();
    }

    renderUI() {
        this.container.innerHTML = `
        <div class="robot-mission">
            <!-- 状态栏 -->
            <div class="status-bar">
                <div class="status-indicator battery-indicator">
                    <i data-lucide="battery"></i>
                    <span>${this.state.battery}%</span>
                </div>
                <div class="status-indicator state-indicator">
                    <i data-lucide="activity"></i>
                    <span>${this.state.status === 'idle' ? '待机' : '工作中'}</span>
                </div>
            </div>

            <!-- 任务执行 -->
            <div class="mission-module">
                <div class="mission-title">任务</div>
                <div class="mission-buttons">
                    <button class="mission-btn" data-action="start">
                        <i data-lucide="play"></i>
                        <span>开始</span>
                    </button>
                    <button class="mission-btn" data-action="pause">
                        <i data-lucide="pause"></i>
                        <span>暂停</span>
                    </button>
                    <button class="mission-btn" data-action="dock">
                        <i data-lucide="home"></i>
                        <span>回充</span>
                    </button>
                    <button class="mission-btn" data-action="spot">
                        <i data-lucide="target"></i>
                        <span>定点</span>
                    </button>
                </div>
            </div>

            <!-- 清扫模式 -->
            <div class="mission-module">
                <div class="mission-title">模式</div>
                <div class="mission-buttons">
                    <button class="mission-btn ${this.state.cleanMode === 'standard' ? 'active' : ''}" data-mode="standard">
                        <i data-lucide="star"></i>
                        <span>标准</span>
                    </button>
                    <button class="mission-btn ${this.state.cleanMode === 'strong' ? 'active' : ''}" data-mode="strong">
                        <i data-lucide="zap"></i>
                        <span>强力</span>
                    </button>
                    <button class="mission-btn ${this.state.cleanMode === 'quiet' ? 'active' : ''}" data-mode="quiet">
                        <i data-lucide="moon"></i>
                        <span>安静</span>
                    </button>
                    <button class="mission-btn ${this.state.cleanMode === 'custom' ? 'active' : ''}" data-mode="custom">
                        <i data-lucide="settings"></i>
                        <span>自定义</span>
                    </button>
                </div>
            </div>

            <!-- 快捷功能 -->
            <div class="mission-module">
                <div class="mission-title">快捷</div>
                <div class="mission-buttons">
                    <button class="mission-btn" data-action="find">
                        <i data-lucide="search"></i>
                        <span>寻找</span>
                    </button>
                    <button class="mission-btn" data-action="map">
                        <i data-lucide="trash-2"></i>
                        <span>清图</span>
                    </button>
                    <button class="mission-btn" data-action="water">
                        <i data-lucide="droplets"></i>
                        <span>水量</span>
                    </button>
                    <button class="mission-btn" data-action="suction">
                        <i data-lucide="wind"></i>
                        <span>吸力</span>
                    </button>
                </div>
            </div>
        </div>
    `;

        // 初始化 Lucide 图标
        lucide.createIcons();
    }

    bindEvents() {
        // 使用事件委托来处理所有按钮点击
        this.container.addEventListener('click', (event) => {
            // 任务执行按钮
            const actionButton = event.target.closest('[data-action]');
            if (actionButton) {
                const action = actionButton.dataset.action;
                this.handleAction(action);
                return;
            }

            // 清扫模式按钮
            const modeButton = event.target.closest('[data-mode]');
            if (modeButton) {
                const mode = modeButton.dataset.mode;
                console.log('Mode button clicked:', mode);
                this.handleModeChange(mode);
                return;
            }
        });

        // 添加按钮激活状态
        const addActiveState = (button) => {
            button.addEventListener('mousedown', () => {
                button.classList.add('active');
            });

            button.addEventListener('mouseup', () => {
                button.classList.remove('active');
            });

            button.addEventListener('mouseleave', () => {
                button.classList.remove('active');
            });
        };

        // 为所有按钮添加激活状态效果
        this.container.querySelectorAll('.mission-btn').forEach(addActiveState);
    }

    handleAction(action) {
        const ws = window.webSocketHandler;
        if (!ws || !ws.isConnected) {
            console.error('WebSocket connection not available');
            return;
        }

        const proto = ws.protobufRoot.mstf.camb.proto;
        const EE_CONTROL_TYPE = proto.EE_CONTROL_TYPE;
        const EE_CMD_FROM_WHO = proto.EE_CMD_FROM_WHO;
        const EE_CLEAN_MODE = proto.EE_CLEAN_MODE;
        const EE_ACT_KEY_TYPE = proto.EE_ACT_KEY_TYPE;

        // 更新状态管理器中的任务状态
        switch (action) {
            case 'start':
                // 更新任务状态
                this.stateManager.updateMissionState('start', {
                    mode: this.state.cleanMode
                });

                // 发送任务开始指令
                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    info: {
                        cmd: EE_CONTROL_TYPE.E_CTRL_TYPE_START,
                        key: EE_ACT_KEY_TYPE.E_KEY_ACT_NULL,
                        user: EE_CMD_FROM_WHO.E_CMD_FROM_H5,
                        mode: EE_CLEAN_MODE.E_CLEAN_GLOBAL,
                        mzp: {
                            // TODO，获取区域数据下发
                            szp: []  // 空数组表示全局清扫
                        }
                    }
                });
                break;

            case 'pause':
                this.stateManager.updateMissionState('pause');
                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    info: {
                        cmd: EE_CONTROL_TYPE.E_CTRL_TYPE_PAUSE,
                        key: EE_ACT_KEY_TYPE.E_KEY_ACT_NULL,
                        user: EE_CMD_FROM_WHO.E_CMD_FROM_H5,
                        mode: EE_CLEAN_MODE.E_CLEAN_GLOBAL
                    }
                });
                break;

            case 'dock':
                this.stateManager.updateMissionState('dock');
                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    info: {
                        cmd: EE_CONTROL_TYPE.E_CTRL_TYPE_FINISH,
                        key: EE_ACT_KEY_TYPE.E_KEY_DOCK,
                        user: EE_CMD_FROM_WHO.E_CMD_FROM_H5,
                        mode: EE_CLEAN_MODE.E_CLEAN_CHARGE
                    }
                });
                break;

            case 'spot':
                this.stateManager.updateMissionState('spot');
                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    info: {
                        cmd: EE_CONTROL_TYPE.E_CTRL_TYPE_START,
                        key: EE_ACT_KEY_TYPE.E_KEY_ACT_NULL,
                        user: EE_CMD_FROM_WHO.E_CMD_FROM_H5,
                        mode: EE_CLEAN_MODE.E_CLEAN_POINT,
                        mzp: {
                            szp: [
                                {
                                    index: 8000,
                                    name: "spot",
                                    areaTyps: proto.EE_AREA_TYPES.E_AREA_TYPE_ALL,
                                    cleanParm: {
                                        fanStrength: this.state.suctionPower,
                                        waterFlow: this.state.waterLevel
                                    }
                                }
                            ]
                        }
                    }
                });
                break;
        }
    }

    // 模式切换处理
    handleModeChange(mode) {
        const ws = window.webSocketHandler;
        if (!ws || !ws.isConnected) {
            console.error('WebSocket connection not available');
            return;
        }

        // 更新本地状态
        this.state.cleanMode = mode;

        // 更新任务状态管理器
        this.stateManager.updateMissionState('updateSettings', {
            currentMode: mode
        });

        // 发送模式切换指令
        ws.sendMessage("MissionCmdGroup", "mission_cmd", {
            command: {
                action: 'SET_MODE',
                params: {
                    mode: mode
                }
            }
        });

        // 更新UI
        this.container.querySelectorAll('[data-mode]').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.mode === mode);
        });
    }

    // 处理底部功能按钮
    handleBottomAction(action) {
        const ws = window.webSocketHandler;
        if (!ws || !ws.isConnected) {
            console.error('WebSocket connection not available');
            return;
        }

        switch (action) {
            case 'water':
                this.state.waterLevel = (this.state.waterLevel % 3) + 1;
                this.stateManager.updateMissionState('updateSettings', {
                    waterLevel: this.state.waterLevel
                });

                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    command: {
                        action: 'SET_WATER_LEVEL',
                        params: {
                            level: this.state.waterLevel
                        }
                    }
                });
                break;

            case 'suction':
                this.state.suctionPower = (this.state.suctionPower % 3) + 1;
                this.stateManager.updateMissionState('updateSettings', {
                    suctionPower: this.state.suctionPower
                });

                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    command: {
                        action: 'SET_SUCTION_POWER',
                        params: {
                            level: this.state.suctionPower
                        }
                    }
                });
                break;

            case 'map':
                if (confirm('确定要删除地图吗？')) {
                    ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                        command: {
                            action: 'CLEAR_MAP'
                        }
                    });
                }
                break;

            case 'find':
                ws.sendMessage("MissionCmdGroup", "mission_cmd", {
                    command: {
                        action: 'FIND_ROBOT'
                    }
                });
                break;
        }
    }

    toggleWaterLevel() {
        const levels = [1, 2, 3];
        this.state.waterLevel = (this.state.waterLevel % 3) + 1;
        this.stateManager.updateComponent('cleaning.waterLevel', this.state.waterLevel);
    }

    toggleSuctionPower() {
        const powers = [1, 2, 3];
        this.state.suctionPower = (this.state.suctionPower % 3) + 1;
        this.stateManager.updateComponent('cleaning.suctionPower', this.state.suctionPower);
    }

    subscribeToStateChanges() {
        this.stateManager.addListener(state => {
            this.updateUI(state);
        });
    }

    updateUI(state) {
        if (!state) return;

        // 更新电池状态
        if (state.working?.batteryLevel !== undefined) {
            const batteryPercent = Math.round(state.working.batteryLevel * 100);
            this.container.querySelector('.battery-status span:last-child').textContent =
                `${batteryPercent}%`;
        }

        // 更新工作状态
        if (state.working?.status) {
            const statusText = state.working.status === 'working' ? '工作中' : '待机';
            this.container.querySelector('.status-item:last-child span:last-child').textContent =
                statusText;
        }

        // 更新清扫模式
        if (state.working?.mode) {
            this.handleModeChange(state.working.mode);
        }
    }

    init() {
        this.renderUI();
        this.bindEvents();
        this.subscribeToStateChanges();
    }

    destroy() {
        if (this.stateManager) {
            this.stateManager.removeListener(this.updateUI.bind(this));
        }
        if (this.container) {
            this.container.innerHTML = '';
        }
    }
}

function initMissionControlPanel() {
    // 检查依赖
    if (typeof MissionControlPanel === 'undefined') {
        console.error('MissionControlPanel class not loaded');
        return null;
    }

    // 获取容器
    const controlInfo = document.getElementById('control-info');
    if (!controlInfo) {
        console.error('Control info container not found');
        return null;
    }

    try {
        // 创建实例
        MissionControlPanel.initialize().then(instance => {
            window.MissionControlPanel = instance;  // 保存到全局变量
            return instance;
        }).catch(error => {
            console.error('Failed to initialize robot control panel:', error);
            return null;
        });
    } catch (error) {
        console.error('Failed to initialize robot control panel:', error);
        return null;
    }
}

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.MissionControlPanel = MissionControlPanel;
    window.initMissionControlPanel = initMissionControlPanel;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        MissionControlPanel,
        initMissionControlPanel
    };
}
